package com.ruoyi.datastatistics.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.basedata.domain.UsersXb;
import com.ruoyi.basedata.mapper.UsersXbMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.datastatistics.domain.*;
import com.ruoyi.datastatistics.mapper.ElectricityMeterHistoryDataMapper;
import com.ruoyi.datastatistics.mapper.MeterHistoryDataMapper;
import com.ruoyi.datastatistics.mapper.PublicShareUserJoinMapper;
import com.ruoyi.datastatistics.service.*;
import com.ruoyi.basedata.domain.vo.UserTerminalsRequestVO;
import com.ruoyi.basedata.domain.vo.UserTerminalsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
/**
 * 公摊用户关联Service业务层处理
 *
 * @author gdqt
 * @date 2025-05-13
 */
@Service
public class PublicShareUserJoinServiceImpl extends ServiceImpl<PublicShareUserJoinMapper, PublicShareUserJoin> implements IPublicShareUserJoinService
{
    @Autowired
    private PublicShareUserJoinMapper publicShareUserJoinMapper;

    @Autowired
    private UsersXbMapper usersXbMapper;

    @Autowired
    private ElectricityMeterHistoryDataMapper electricityMeterHistoryDataMapper;
    @Autowired
    private MeterHistoryDataMapper meterHistoryDataMapper;
    @Autowired
    private IElectricityRealtimegatherdataXbService electricityRealtimegatherdataXbService;
    @Autowired
    private IRealtimegatherdataXbService realtimegatherdataXbService;


    /**
     * 查询公摊用户关联
     *
     * @param id 公摊用户关联主键
     * @return 公摊用户关联
     */
    @Override
    public PublicShareUserJoin selectPublicShareUserJoinById(Long id)
    {

        return publicShareUserJoinMapper.selectById(id);
    }

    /**
     * 查询公摊用户关联列表
     *
     * @param publicShareUserJoin 公摊用户关联
     * @return 公摊用户关联
     */
    @Override
    public List<PublicShareUserJoin> selectPublicShareUserJoinList(PublicShareUserJoin publicShareUserJoin)
    {
        LambdaQueryWrapper<PublicShareUserJoin> queryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(publicShareUserJoin.getTenantId())){
            queryWrapper.eq(PublicShareUserJoin::getTenantId,publicShareUserJoin.getTenantId());
        }
        if(!StringUtils.isEmpty(publicShareUserJoin.getPublicShareId())){
            queryWrapper.eq(PublicShareUserJoin::getPublicShareId,publicShareUserJoin.getPublicShareId());
        }
        if(publicShareUserJoin.getEnergyType() != null){
            queryWrapper.eq(PublicShareUserJoin::getEnergyType,publicShareUserJoin.getEnergyType());
        }
        if(!StringUtils.isEmpty(publicShareUserJoin.getUserId())){
            queryWrapper.eq(PublicShareUserJoin::getUserId,publicShareUserJoin.getUserId());
        }
        if(!StringUtils.isEmpty(publicShareUserJoin.getTerminalId())){
            queryWrapper.eq(PublicShareUserJoin::getTerminalId,publicShareUserJoin.getTerminalId());
        }
        if(publicShareUserJoin.getPublicShareType() != null){
            queryWrapper.eq(PublicShareUserJoin::getPublicShareType,publicShareUserJoin.getPublicShareType());
        }
        if(publicShareUserJoin.getCalcType() != null){
            queryWrapper.eq(PublicShareUserJoin::getCalcType,publicShareUserJoin.getCalcType());
        }
        return publicShareUserJoinMapper.selectList(queryWrapper);
    }

    /**
     * 新增公摊用户关联
     *
     * @param publicShareUserJoin 公摊用户关联
     * @return 结果
     */
    @Override
    public int insertPublicShareUserJoin(PublicShareUserJoin publicShareUserJoin)
    {
        return publicShareUserJoinMapper.insert(publicShareUserJoin);
    }

    @Override
    public int cloneinsertPublicShareUserJoin(String oldUserId, String newUserId)
    {
        return publicShareUserJoinMapper.cloneinsert(oldUserId,newUserId);
    }

    /**
     * 修改公摊用户关联
     *
     * @param publicShareUserJoin 公摊用户关联
     * @return 结果
     */
    @Override
    public int updatePublicShareUserJoin(PublicShareUserJoin publicShareUserJoin)
    {
        return publicShareUserJoinMapper.updateById(publicShareUserJoin);
    }

    /**
     * 批量删除公摊用户关联
     *
     * @param ids 需要删除的公摊用户关联主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePublicShareUserJoinByIds(Long[] ids)
    {
        return publicShareUserJoinMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public void deletePublicShareUserJoinByUser(String userId)
    {
         publicShareUserJoinMapper.deletePublicShareUserJoinByUser(userId);
    }


    /**
     * 删除公摊用户关联信息
     *
     * @param id 公摊用户关联主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePublicShareUserJoinById(Long id)
    {
        return publicShareUserJoinMapper.deleteById(id);
    }

    @Override
    public List<PublicShareUserJoin> selectListWithUser(PublicShareUserJoin publicShareUserJoin) {
        return publicShareUserJoinMapper.selectListWithUser2(publicShareUserJoin);
    }

    @Override
    public List<UsersXb> getUserListInSelect(String tenantId) {
        return usersXbMapper.selectList(new LambdaQueryWrapper<UsersXb>().eq(UsersXb::getTenantId,tenantId).eq(UsersXb::getDelFlag,0)
                .eq(UsersXb::getUserMark,1).orderByAsc(UsersXb::getUserId));
    }

    @Override
    public List<UsersXb> getUserPageForGJ(PublicShareUserJoin publicShareUserJoin) {
        return publicShareUserJoinMapper.getUserPageForGJ(publicShareUserJoin);
    }

    @Override
    public List<Map<String, Object>> getUserPageForGJProduct(PublicShareUserJoin publicShareUserJoin) {
        return publicShareUserJoinMapper.getUserPageForGJProduct(publicShareUserJoin);
    }

    /**
     * 弃用，迁移到USERXB
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> getUserTerminalInPublicShareList(String userId) {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("userTerminalList", null);
        resMap.put("otherTerminalList", null);
        //查找用户下所有关联的公摊
        List<PublicShareUserJoin> psJoinList = publicShareUserJoinMapper.selectList(new LambdaQueryWrapper<PublicShareUserJoin>()
                .eq(PublicShareUserJoin::getUserId,userId));
        if(psJoinList != null && !psJoinList.isEmpty()){
            //获取用户绑定的公摊ID
            List<String> publicShareIds = psJoinList.stream().map(PublicShareUserJoin::getPublicShareId).distinct().collect(Collectors.toList());
            //查找公摊下所有绑定的用户,而且是在场的
            List<PublicShareUserJoin> psJoinList2 = publicShareUserJoinMapper.selectList(new LambdaQueryWrapper<PublicShareUserJoin>()
                    .in(PublicShareUserJoin::getPublicShareId,publicShareIds).eq(PublicShareUserJoin::getStatus,1));
            //获取所有用户ID
            List<String> userIds = psJoinList2.stream().map(PublicShareUserJoin::getUserId).distinct().collect(Collectors.toList());
            //查找用户挂接的设备
            List<UserTerminalsVO> list = publicShareUserJoinMapper.getUserTerminalsForGj(userIds);
            Map<String,List<UserTerminalsVO>> userTemrinalMap = list.stream().collect(Collectors.groupingBy(UserTerminalsVO::getUserId));
            if(userTemrinalMap.containsKey(userId)){
                List<UserTerminalsVO> userTemrinalList = userTemrinalMap.get(userId);
                resMap.put("userTerminalList", userTemrinalList);
                userTemrinalMap.remove(userId);
                List<UserTerminalsVO> otherTerminalsList = new ArrayList<>();
                for (String key : userTemrinalMap.keySet()) {
                    otherTerminalsList.addAll(userTemrinalMap.get(key));
                }
                resMap.put("otherTerminalList", otherTerminalsList);
            }
        }
        return resMap;
    }

    /**
     * 弃用
     * @param requestVO
     * @return
     */
    @Override
    public int dealUserLeave(UserTerminalsRequestVO requestVO) {
        String userId = requestVO.getUserId();
        //离场用户信息
        List<UserTerminalsVO> ownUserTerminalList = requestVO.getOwnUserTerminalList();
        //离场用户关联公摊其他用户信息
        List<UserTerminalsVO> publicTerminalList = requestVO.getPublicTerminalList();
        //离场用户信息
        List<UserTerminalsVO> publicUserTerminalList = requestVO.getPublicUserTerminalList();
        //手动抄表数据录入到历史表和实时表中
        for(UserTerminalsVO vo : ownUserTerminalList){
            insertMeterHistoryDataAndRealData(vo);
        }
        for(UserTerminalsVO vo : publicTerminalList){
            insertMeterHistoryDataAndRealData(vo);
        }
        for(UserTerminalsVO vo : publicUserTerminalList){
            insertMeterHistoryDataAndRealData(vo);
        }
        //更改用户状态
        UsersXb usersXb = new UsersXb();
        usersXb.setUserMark(0);
        usersXb.setDepartureTime(DateUtils.getNowDate());
        usersXbMapper.update(usersXb, new LambdaUpdateWrapper<UsersXb>().eq(UsersXb::getUserId,userId));
        //更改公摊中用户状态
        PublicShareUserJoin publicShareUserJoin = new PublicShareUserJoin();
        publicShareUserJoin.setStatus(2);
        publicShareUserJoin.setUpdateTime(DateUtils.getNowDate());
        publicShareUserJoinMapper.update(publicShareUserJoin, new LambdaUpdateWrapper<PublicShareUserJoin>().eq(PublicShareUserJoin::getUserId,userId));
        //调用用量报表，开账报表，开账明细报表，公摊报表，公摊明细报表接口
        //TODO 调用别的接口


        return 1;
    }
    /**
     * 插入历史、实时数据
     * @param requestVO
     * @return
     */
    @Override
    public int insertHistoryDataAndRealData(UserTerminalsRequestVO requestVO) {
        String userId = requestVO.getUserId();
        //离场用户信息
        List<UserTerminalsVO> ownUserTerminalList = requestVO.getOwnUserTerminalList();
        //离场用户关联公摊其他用户信息
        List<UserTerminalsVO> publicTerminalList = requestVO.getPublicTerminalList();
        //离场用户信息
        List<UserTerminalsVO> publicUserTerminalList = requestVO.getPublicUserTerminalList();
        //手动抄表数据录入到历史表和实时表中
        for(UserTerminalsVO vo : ownUserTerminalList){
            insertMeterHistoryDataAndRealData(vo);
        }
        for(UserTerminalsVO vo : publicTerminalList){
            insertMeterHistoryDataAndRealData(vo);
        }
        for(UserTerminalsVO vo : publicUserTerminalList){
            insertMeterHistoryDataAndRealData(vo);
        }
        //更改用户状态
        UsersXb usersXb = new UsersXb();
        usersXb.setUserMark(0);
        usersXb.setDepartureTime(DateUtils.getNowDate());
        usersXbMapper.update(usersXb, new LambdaUpdateWrapper<UsersXb>().eq(UsersXb::getUserId,userId));
        //更改公摊中用户状态
        PublicShareUserJoin publicShareUserJoin = new PublicShareUserJoin();
        publicShareUserJoin.setStatus(2);
        publicShareUserJoin.setUpdateTime(DateUtils.getNowDate());
        publicShareUserJoinMapper.update(publicShareUserJoin, new LambdaUpdateWrapper<PublicShareUserJoin>().eq(PublicShareUserJoin::getUserId,userId));
        //调用用量报表，开账报表，开账明细报表，公摊报表，公摊明细报表接口
        //TODO 调用别的接口


        return 1;
    }

    /**
    * @Description: 插入电数据
    * @date: 2025/7/11 09:52
    * @author: zt
    */
    @Override
    public void insertMeterHistoryDataAndRealData(UserTerminalsVO userTerminalsVO)
    {
        Integer energyType = userTerminalsVO.getEnergyType();
        if(energyType == 1){
            ElectricityMeterHistoryData meterHistoryData = new ElectricityMeterHistoryData();
            meterHistoryData.setTenantId(userTerminalsVO.getTenantId());
            meterHistoryData.setUserId(userTerminalsVO.getUserId());
            meterHistoryData.setTerminalId(userTerminalsVO.getTerminalId());
            meterHistoryData.setLocationNb(userTerminalsVO.getLocationNb());
            meterHistoryData.setCombinationActiveEnergy1(userTerminalsVO.getTotalFlow());
            meterHistoryData.setReadDate(userTerminalsVO.getReadDate());
            //属性转换
            ElectricityRealtimegatherdataXb electricityRealtimegatherdataXb = new ElectricityRealtimegatherdataXb();
            BeanUtils.copyProperties(meterHistoryData,electricityRealtimegatherdataXb);
            electricityMeterHistoryDataMapper.insert(meterHistoryData);
            //删除实时数据存在的数据
            electricityRealtimegatherdataXbService.getBaseMapper().delete(new LambdaQueryWrapper<ElectricityRealtimegatherdataXb>()
                    .eq(ElectricityRealtimegatherdataXb::getLocationNb,meterHistoryData.getLocationNb()));
            //插入新的实时数据
            electricityRealtimegatherdataXbService.insertRealtimegatherdataXb(electricityRealtimegatherdataXb);
        } else if (energyType == 2) {
            MeterHistoryData meterHistoryData = new MeterHistoryData();
            meterHistoryData.setTenantId(userTerminalsVO.getTenantId());
            meterHistoryData.setUserId(userTerminalsVO.getUserId());
            meterHistoryData.setTerminalId(userTerminalsVO.getTerminalId());
            meterHistoryData.setLocationNb(userTerminalsVO.getLocationNb());
            meterHistoryData.setTotalFlow(userTerminalsVO.getTotalFlow());
            meterHistoryData.setReadNumber(userTerminalsVO.getReadNumber());
            meterHistoryData.setReverseNumber(userTerminalsVO.getReverseNumber());
            meterHistoryData.setReadDate(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",userTerminalsVO.getReadDate()));

            //属性转换
            RealtimegatherdataXb realtimegatherdataXb = new RealtimegatherdataXb();
            BeanUtils.copyProperties(meterHistoryData,realtimegatherdataXb);
            realtimegatherdataXb.setReadDate(DateUtils.parseDate(meterHistoryData.getReadDate()));
            meterHistoryDataMapper.insert(meterHistoryData);
            //删除实时数据存在的数据
            realtimegatherdataXbService.getBaseMapper().delete(new LambdaQueryWrapper<RealtimegatherdataXb>()
                    .eq(RealtimegatherdataXb::getLocationNb,meterHistoryData.getLocationNb()));
            //插入新的实时数据
            realtimegatherdataXbService.insertRealtimegatherdataXb(realtimegatherdataXb);
        }
    }
}
